/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.tnmk.common.util.file.FileMovingUtils;
import org.tnmk.common.util.file.IoUtils;
import org.tnmk.worktime.service.model.xmladapter.ListWrapper;
import org.tnmk.worktime.service.model.xmlconverter.XmlUtils;
import org.tnmk.worktime.utils.TimeUtils;

/**
 *
 * @author Administrator
 */
public final class IoService {

  private static final IoService INSTANCE = new IoService();

  public static IoService getInstance() {
    return INSTANCE;
  }

  private final Logger log = Logger.getLogger(this.getClass().getSimpleName() + "@" + this.hashCode());
  private static final String DATA_FILE_EXTENSION = ".dly";
  private static final File DATA_FILE = new File("data/history" + DATA_FILE_EXTENSION);

  private IoService() {
  }

  public void backupData() {
    try {
      DateTime currentTime = DateTime.now();
      String stime = TimeUtils.toString(currentTime, "yyyy-MM-dd_a-hh-mm-ss");
      File backupFile = new File("../WorkTimeBackup/history_" + stime + DATA_FILE_EXTENSION);
      FileMovingUtils.copyOnePath(DATA_FILE, backupFile, true);
    } catch (IOException ex) {
      log.error("Cannot backupData", ex);
    }
  }

  public <E extends Serializable> void saveHistoryToFile(List<E> history) throws IOException {
    XmlUtils.marshallToFile(new ListWrapper(history), DATA_FILE);
  }

  public <E extends Serializable> void saveHistoryToFile(
          List<E> previousSessionHistory,
          E model) throws IOException {
    List<E> saveList = new ArrayList<>(previousSessionHistory.size() + 1);
    saveList.addAll(previousSessionHistory);
    saveList.add(model);
    String historyXml = XmlUtils.marshall(new ListWrapper(saveList));
    IoUtils.saveString(historyXml, DATA_FILE);
    log.debug("Save File: " + DATA_FILE.getAbsolutePath());
  }

  public <E extends Serializable> List<E> loadHistoryFromFile() {
    List<E> history = null;
    if (!DATA_FILE.exists()) {
      log.error("Cannot load history from file (programme still continuous normally): " + DATA_FILE.getAbsolutePath());
    }
    ListWrapper listWrapper = (ListWrapper) XmlUtils.unmarshallFromFile(DATA_FILE);
    if (listWrapper != null) {
      history = listWrapper.getItems();
    }
    if (history == null) {
      history = new ArrayList<>();
    }
    return history;
  }
}
